<template>
    <div class="app-container">
        <el-row :gutter="0">
            <!--专病数据-->
            <el-form class="formBox searchForm" :model="queryParams" ref="queryForm" size="small" :inline="true"
                v-show="showSearch" label-width="68px">
                <el-form-item label="医院" prop="hospital" clearable>
                    <department :isHospital="true" :isdepat="true" @refreshData="refreshData" deptWidth="200px"
                        ref="department"></department>
                </el-form-item>

                <el-form-item label="设备名称" prop="deviceName">
                    <el-input v-model="queryParams.deviceName" placeholder="请输入设备名称" clearable style="width:200px"
                        @keyup.enter.native="handleQuery" />
                </el-form-item>
                <el-form-item label="设备类别" prop="deviceType" clearable>
                    <el-select v-model="queryParams.deviceType" placeholder="类别" clearable filterable style="width: 200px">
                        <el-option v-for="dict in dict.type.sys_device_type" :key="dict.value" :label="dict.label"
                            :value="dict.value" />
                    </el-select>
                </el-form-item>
                <el-form-item label="状态" prop="status" clearable>
                    <el-select v-model="queryParams.status" placeholder="状态" clearable filterable style="width: 200px">
                        <el-option v-for="dict in sysUseTypeArr" :key="dict.value" :label="dict.label"
                            :value="dict.value" />
                    </el-select>
                </el-form-item>

                <el-form-item>
                    <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                    <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
                </el-form-item>
            </el-form>

            <div class="formBox searchForm" ref="statisticalTable" style="margin-bottom:0px!important;">
                <el-row :gutter="10" class="mb8">
                    <el-col :span="1.5">
                        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
                            v-hasPermi="['system:device:add']">新增</el-button>
                        <el-button type="success" plain icon="el-icon-plus" size="mini"
                            @click="platformTempDialogVisible = true" v-hasPermi="['system:device:temp']">引入平台模板</el-button>
                    </el-col>

                    <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
                </el-row>

                <el-table v-loading="loading" :data="classifyList" border :height="statisticalTableH" ref="table">
                    <!--                <el-table-column type="selection" width="50" align="center" />-->
                    <el-table-column sortable label="设备编号" align="center" prop="deviceId" width="100" />
                    <el-table-column label="设备类别" align="center" prop="deviceType" :show-overflow-tooltip="true"
                        width="150">
                        <template slot-scope="scope">
                            <dict-tag :options="dict.type.sys_device_type" :value="scope.row.deviceType" />
                        </template>
                    </el-table-column>
                    <el-table-column label="医院" align="center" prop="hospitalName" :show-overflow-tooltip="true"
                        width="150">
                        <template slot-scope="scope">
                            <departTag :options="deptNameLists" :value="scope.row.hospitalId" />
                        </template>
                    </el-table-column>
                    <el-table-column label="科室" align="center" prop="deptName" :show-overflow-tooltip="true" width="150">
                        <template slot-scope="scope">
                            <departTag :options="deptNameLists" :value="scope.row.deptId" />
                        </template>
                    </el-table-column>

                    <el-table-column label="设备名称" align="center" prop="deviceName" :show-overflow-tooltip="true"
                        width="300" />
                    <el-table-column label="品牌" align="center" prop="deviceBrand" :show-overflow-tooltip="true" />
                    <el-table-column label="型号" align="center" prop="deviceModel" :show-overflow-tooltip="true" />
                    <el-table-column label="产地" align="center" prop="deviceArea" :show-overflow-tooltip="true" />
                    <el-table-column label="状态" align="center" prop="deviceType" :show-overflow-tooltip="true" width="150">
                        <template slot-scope="scope">
                            <span v-if="scope.row.status == '1'" style="color:red">停用</span>
                            <span v-else style="color:green">正常</span>
                        </template>
                    </el-table-column>
                    <el-table-column sortable label="创建时间" align="center" prop="createTime" width="160">
                        <template slot-scope="scope">
                            <span>{{ parseTime(scope.row.createTime) }}</span>
                        </template>
                    </el-table-column>
                    <!-- <el-table-column  label="备注" align="center" prop="remark" :show-overflow-tooltip="true" /> -->
                    <el-table-column label="操作" align="center" fixed="right" width="160"
                        class-name="small-padding fixed-width">
                        <template slot-scope="scope">
                            <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
                                v-hasPermi="['system:device:edit']">修改</el-button>
                            <el-button size="mini" type="text" icon="" @click="handleUpdateStatus(scope.row)"
                                v-hasPermi="['system:device:use']">{{ scope.row.status == '1' ? '启用' : '停用' }}</el-button>
                            <!--                            <el-button size="mini" type="text" icon="el-icon-delete"-->
                            <!--                                @click="handleDelete(scope.row)">删除</el-button>-->
                        </template>
                    </el-table-column>
                </el-table>
                <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
                    :limit.sync="queryParams.pageSize" @pagination="getList" />
            </div>

        </el-row>

        <!-- 添加或修改对话框 -->
        <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body :before-close="cancel"
            :close-on-click-modal="false">
            <el-form ref="form" :model="form" :rules="rules" label-width="80px" label-position="left" class="formBox1">
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="设备名称" prop="deviceName">
                            <el-input v-model="form.deviceName" placeholder="请输入设备名称" clearable style="width:480px" />
                        </el-form-item>
                    </el-col>

                </el-row>
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="使用科室" prop="deptId" v-if="open">
                            <department :isAdd="true" @changedepatData="changedepatData" :HospitalId="form.hospitalId"
                                :Optiohospitals="true" :deptIds="form.deptId" :isdisabled="false"></department>
                        </el-form-item>
                    </el-col>

                </el-row>

                <el-row>
                    <el-col :span="10">
                        <el-form-item label="产地">
                            <el-input v-model="form.deviceArea" placeholder="请输入产地" style="width:150px"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="1"><el-form-item></el-form-item></el-col>
                    <el-col :span="12">
                        <el-form-item label="品牌" label-width="50px">
                            <el-input v-model="form.deviceBrand" placeholder="请输入品牌" style="width:250px"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="10">
                        <el-form-item label="设备类别" prop="deviceType">
                            <el-select v-model="form.deviceType" placeholder="类别" clearable filterable style="width: 150px"
                                :disabled="form.deviceId && !isAdmin ? true : false">
                                <el-option v-for="dict in dict.type.sys_device_type" :key="dict.value" :label="dict.label"
                                    :value="dict.value" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="1"><el-form-item></el-form-item></el-col>
                    <el-col :span="12">
                        <el-form-item label="型号" label-width="50px">
                            <el-input v-model="form.deviceModel" placeholder="请输入型号" style="width:250px"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>


                <el-row v-if="form.deviceType == 1">
                    <el-col :span="24">
                        <el-form-item label="选择检测的指标" label-width="120px" prop="detectionIds">
                            <el-select v-model="form.detectionIds" multiple filterable placeholder="选择检测的指标"
                                style="width:440px">
                                <el-option v-for="dict in detectionType" :key="dict.detectionId" :label="dict.detectionName"
                                    :value="dict.detectionId" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>

            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="submitForm">保 存</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </el-dialog>
        <!-- 引入平台模板 -->
        <el-dialog :title="platformTitle" :visible.sync="platformTempDialogVisible" v-dialogDrag width="90%"
            :close-on-click-modal="false">
            <platformTemp v-if="platformTempDialogVisible" @closeplatformTempDialogVisible="closeplatformTempDialogVisible"
                type="2" @refresh="refreshFormList">
            </platformTemp>
        </el-dialog>


    </div>
</template>

<script>
import department from "@/views/components/department/index.vue";
import departTag from "@/views/components/department/departTag.vue";
import { listDevice, getDevice, delDevice, addDevice, updateDevice, getDeviceUpdateStatus } from "@/api/system/device";
import { listDetection } from "@/api/system/detection";
import { deptNameList } from "@/api/system/dept";
import { getToken } from "@/utils/auth";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import platformTemp from "@/views/components/platformTemp/deviceTemp.vue";


export default {
    name: "deviceList",
    dicts: ["sys_device_type"],
    components: { department, departTag, platformTemp },
    data() {
        return {
            statisticalTableH: undefined,
            platformTempDialogVisible: false,
            platformTitle: '平台模板-设备',
            // 遮罩层
            loading: true,
            // 选中数组
            ids: [],
            diseaseClassifyName: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            // 专病表格数据
            classifyList: null,
            // 弹出层标题
            title: "",
            // 是否显示弹出层
            open: false,
            // 日期范围
            dateRange: [],
            // 是否修改
            inputDisabled: false,
            // 表单参数
            // form: {},
            form: {
                deviceName: '',//设备名称
                deviceArea: '',//产地
                deviceBrand: '',//品牌
                deviceType: '',//设备类别  0 治疗 1 检测
                deviceModel: '',//型号
                detectionIds: [],//已选的 检测指标 JSON.stringify 传给后台
                deptId: undefined,
                hospitalId: undefined
            },
            sysUseTypeArr: [
                { label: '正常', value: '0' },
                { label: '停用', value: '1' }
            ],
            detectionType: [],//可选的 检测指标  （接口返回）仅前端用
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                deviceName: undefined,
                status: undefined,
                deviceType: undefined,
                hospitalId: undefined,
                deptId: undefined,
            },
            deptNameLists: [],
            // 表单校验
            rules: {
                deviceName: [
                    {
                        required: true,
                        message: "设备名称不能为空",
                        trigger: "blur",
                    },
                ],
                deviceType: [
                    {
                        required: true,
                        message: "设备类别必选",
                        trigger: "blur",
                    },
                ],
                detectionIds: [
                    {
                        required: true,
                        message: "检测指标必选",
                        trigger: "blur",
                    },
                ],
                deptId: [
                    {
                        required: true,
                        message: "科室必选",
                        trigger: "blur",
                    },
                ],
            },
            //是否数组



        };
    },
    watch: {
        showSearch() {
            this.$nextTick(() => {
                this.changeHeight()
            }, 1000)

        }
    },
    created() {
        this.getDetectionType();

        this.loading = false;
    },
    mounted() {
        this.changeHeight()
    },
    computed: {
        isAdmin() {
            return this.$store.state.user.name === 'admin' ? true : false
        }
    },
    updated() {
        this.$nextTick(() => {
            this.$refs.table.doLayout()
        })
    },
    methods: {
        changeHeight() {
            if (this.$refs.statisticalTable) {
                const statisticalTableObj = this.$refs.statisticalTable.getBoundingClientRect();
                let h = statisticalTableObj.top + 100
                this.statisticalTableH = 'calc(100vh - ' + h + 'px)'
            } else {
                this.statisticalTableH = '500px'
            }
        },
        /** 平台模板引用或者批量引用点击后关闭弹窗并刷新本院表单列表 */
        refreshFormList() {
            this.platformTempDialogVisible = false
            this.getList()
        },
        closeplatformTempDialogVisible() {
            this.platformTempDialogVisible = false
        },
        refreshData(data) {
            this.queryParams.pageNum = 1;
            this.queryParams.hospitalId = data.hospitalId
            this.queryParams.deptId = data.deptId
            this.getdeptNameList();

        },
        changedepatData(data) {
            if (data && data.length > 0) {
                this.form.deptId = data[0].deptId
                this.form.hospitalId = data[0].parentId == 100 ? data[0].deptId : data[0].parentId
            } else {
                this.form.deptId = undefined
                this.form.hospitalId = undefined
            }
        },
        // 回显医院及门诊
        getdeptNameList() {
            deptNameList().then((response) => {
                console.log(response.data)
                this.deptNameLists = response.data;
                this.getList();
            });
        },
        /** 查询指标列表 */
        getDetectionType() {
            let params = {
                pageNum: 1,
                pageSize: 9999,
            }
            listDetection(
                params
            ).then((response) => {
                console.log(response.rows)
                this.detectionType = response.rows;
            });
        },
        /** 查询设备列表 */
        getList() {
            this.loading = true;
            listDevice(
                this.queryParams
            ).then((response) => {
                this.classifyList = response.rows;
                this.total = response.total;
                this.loading = false;
            });
        },
        // 取消按钮
        cancel() {
            this.open = false;
            this.reset();
        },

        // 表单重置
        reset() {
            this.form = {
                deviceName: '',//设备名称
                deviceArea: '',//产地
                deviceBrand: '',//品牌
                deviceType: '',//设备类别  0 治疗 1 检测
                deviceModel: '',//型号
                detectionIds: [],//已选的 检测指标 JSON.stringify 传给后台[]
                deptId: undefined,
                hospitalId: undefined
            };
            this.resetForm("form");
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1;
            this.getList();
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.dateRange = [];
            this.resetForm("queryForm");
            if (this.$refs.department) {
                this.$refs.department.reset()
            }
            // this.handleQuery();
        },

        /** 新增按钮操作 */
        handleAdd() {
            this.reset();
            this.inputDisabled = false
            this.open = true;
            this.title = "新增设备";
        },
        /** 修改按钮操作 */
        handleUpdate(row) {
            this.reset();
            this.inputDisabled = true
            const deviceId = row.deviceId;
            getDevice(deviceId).then((response) => {
                this.form = response.data;
                this.open = true;
                this.title = "修改设备";
            });
        },

        /** 提交按钮 */
        submitForm: function () {
            // this.$modal.msgSuccess("新增成功！");
            console.log(this.form.detectionIds)
            this.$refs["form"].validate((valid) => {
                if (valid) {
                    if (this.form.deviceId != undefined) {
                        updateDevice(this.form).then((response) => {
                            this.$modal.msgSuccess("修改成功");
                            this.open = false;
                            this.getList();
                        });
                    } else {
                        addDevice(this.form).then((response) => {
                            this.$modal.msgSuccess("新增成功");
                            this.open = false;
                            this.getList();
                        });
                    }
                }
            });
        },
        /**启用或者停用按钮操作 */
        handleUpdateStatus(row) {
            const deviceName = row.deviceName
            const deviceId = row.deviceId;
            const text = row.status == '1' ? '启用' : '停用'
            const status = row.status == '1' ? '0' : '1'
            this.$modal
                .confirm(
                    '是否确认' + text + '设备名称为"' +
                    deviceName +
                    '"的数据项？'
                )
                .then(function () {
                    // let params={
                    //     deviceId:deviceId,
                    //     status:row.status
                    // }
                    return getDeviceUpdateStatus(deviceId, status);
                })
                .then(() => {
                    this.getList();
                    this.$modal.msgSuccess("操作成功");
                })
                .catch(() => { });
        },
        /** 删除按钮操作 */
        handleDelete(row) {
            const deviceName = row.deviceName
            const deviceId = row.deviceId;
            this.$modal
                .confirm(
                    '是否确认删除设备名称为"' +
                    deviceName +
                    '"的数据项？'
                )
                .then(function () {
                    return delDevice(deviceId);
                })
                .then(() => {
                    this.getList();
                    this.$modal.msgSuccess("删除成功");
                })
                .catch(() => { });
        },

    },
};
</script>
<style scoped>
.el-tag {
    margin-right: 15px;
}
</style>
